package com.vmove.childtrain.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.vmove.childtrain.R;
import com.vmove.childtrain.common.BaseActivity;
import com.vmove.childtrain.common.BaseFragment;
import com.vmove.childtrain.common.BaseSerialActivity;
import com.vmove.childtrain.common.Constants;
import com.vmove.childtrain.common.ScreenStatusReceiver;
import com.vmove.childtrain.db.dao.LightDao;
import com.vmove.childtrain.db.dao.ProgramDao;
import com.vmove.childtrain.db.dao.SettingDao;
import com.vmove.childtrain.db.dao.TeamDao;
import com.vmove.childtrain.db.dao.UserDao;
import com.vmove.childtrain.db.data.InitData;
import com.vmove.childtrain.db.entity.Light;
import com.vmove.childtrain.db.entity.Setting;
import com.vmove.childtrain.fragment.FirstFragment;
import com.vmove.childtrain.fragment.FragmentFactory;
import com.vmove.childtrain.protocol.CommandType;
import com.vmove.childtrain.utils.AutoUtils;
import com.vmove.childtrain.utils.SharedPreferences;
import com.vmove.childtrain.view.LightView;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends BaseSerialActivity {


    @BindView(R.id.fragmentContainer) FrameLayout fragmentContainer;
    @BindView(R.id.tabView) BottomNavigationView tabView;

    FragmentManager fragmentManager;
    private ArrayList<String> fragmentTags;
    private int currIndex;
    private static final String CURR_INDEX = "currIndex";
    private SharedPreferences sp;
    private LightDao lightDao;
    private ProgramDao programDao;
    private SettingDao settingDao;
    private UserDao userDao;
    private TeamDao teamDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        fragmentManager = getSupportFragmentManager();
        initData(savedInstanceState);
        lightDao = new LightDao(this);
        programDao = new ProgramDao(this);
        userDao = new UserDao(this);
        teamDao = new TeamDao(this);
        settingDao = new SettingDao(this);
        initView();
        checkFirstStart();
        readSetting();
        registScreenStatusReceiver();
    }

    private ScreenStatusReceiver screenStatusReceiver;

    private void registScreenStatusReceiver(){
        screenStatusReceiver = new ScreenStatusReceiver(this);
        IntentFilter screenStatusFilter = new IntentFilter();
        screenStatusFilter.addAction(Intent.ACTION_SCREEN_OFF);
        screenStatusFilter.addAction(Intent.ACTION_SCREEN_ON);
        screenStatusFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(screenStatusReceiver, screenStatusFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(screenStatusReceiver);
    }

    private void checkFirstStart(){
        sp = SharedPreferences.getInstance();
        boolean isFirstStart = sp.getBoolean(Constants.SP_ISFIRSTSTART, true);
        if (isFirstStart){
            //判断表里有没有数据
            sp.putBoolean(Constants.SP_ISFIRSTSTART, false);
            try {
                List<Light> allLights = lightDao.getAllLights();
                if (null==allLights || allLights.size()==0){
                    initDatabase();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  读取setting配置
     */
    private void readSetting() {
        Setting padIdSetting = settingDao.getSettingByName(Setting.NAME_PADID);
        Setting yanShiSettig = settingDao.getSettingByName(Setting.NAME_INTERVAL);
        if (null!=padIdSetting){
            String padId = padIdSetting.getSettingValue();
            Constants.PADID = Short.parseShort(padId);
        }

        if (null!=yanShiSettig){
            String yanShi = yanShiSettig.getSettingValue();
            Constants.COMMAND_INTERVAL = Integer.parseInt(yanShi);
        }
    }

    @Override
    public void onSerialReceivedData(byte[] data) {
        if (data.length<8) {
            return;
        }
        if (data[5] == CommandType.COMMAND_LIGHTSTATUS_R){
            //查询灯状态的回复 推送给fragment1
            BaseFragment fragment = (FirstFragment) FragmentFactory.getFragment(0);
            if (null!=fragment){
                fragment.setSerialReceivedData(data);
            }
        }
    }

    /**
     * 初始化测试数据
     */
    private void initDatabase(){
        InitData initData = new InitData();
        List<Light> lights = initData.initLight();
        lightDao.createAll(lights);
        programDao.addProgram(initData.getLessonProgram1());
        programDao.addProgram(initData.getLessonProgram2());
        programDao.addProgram(initData.getLessonProgram3());
        programDao.addProgram(initData.getLessonProgram4());
        teamDao.createAll(initData.getTestTeam());
        userDao.createAll(initData.getTestUsers());
    }


    private void initView() {
//        tabView.setItemIconTintList(null);//关闭icon颜色切换
        tabView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.tab_one:
                        currIndex=0;
                        break;
                    case R.id.tab_two:
                        currIndex=1;
                        break;
                    case R.id.tab_three:
                        currIndex=2;
                        break;
                }
                showFragment();
                return true;
            }
        });
        showFragment();
    }

    private void initData(Bundle savedInstanceState) {
        fragmentTags = new ArrayList<>(Arrays.asList(getString(R.string.tabTitle1),
                getString(R.string.tabTitle2)
                ,getString(R.string.tabTitle3)));
        currIndex = 0;
        if (savedInstanceState != null) {
            currIndex = savedInstanceState.getInt(CURR_INDEX);
            hideSavedFragment();
        }
    }

    private void hideSavedFragment() {
        Fragment fragment = fragmentManager.findFragmentByTag(fragmentTags.get(currIndex));
        if (fragment != null) {
            fragmentManager.beginTransaction().hide(fragment).commit();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(CURR_INDEX, currIndex);
    }

    private void showFragment() {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment = fragmentManager.findFragmentByTag(fragmentTags.get(currIndex));
        if (fragment == null) {
            fragment = FragmentFactory.createFragment(currIndex);
        }
        for (int i = 0; i < fragmentTags.size(); i++) {
            Fragment f = fragmentManager.findFragmentByTag(fragmentTags.get(i));
            if (f != null && f.isAdded()) {
                fragmentTransaction.hide(f);
            }
        }
        if (fragment.isAdded()) {
            fragmentTransaction.show(fragment);
        } else {
            fragmentTransaction.add(R.id.fragmentContainer, fragment, fragmentTags.get(currIndex));
        }
//        fragmentTransaction.commit();
        fragmentTransaction.commitAllowingStateLoss();
//        fragmentTransaction.commitNowAllowingStateLoss();//api24之后修复fragment重叠
        fragmentManager.executePendingTransactions();
        setTitle(fragmentTags.get(currIndex));
    }

    @Override
    public String returnToolBarTitle() {
        return null;
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis()-exitTime) > 2000){
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                if (null!=customSerialDriver && customSerialDriver.isConnect()){
                    customSerialDriver.closeSerial();
                }
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
